<template>
  <div class="custom-transfer">
    <!-- 左侧列表 -->
    <div class="transfer-panel">
      <div class="panel-header">
        <span class="title">{{ sourceTitle }}</span>
        <div class="search-box">
          <a-input-search
            v-model="sourceSearchText"
            :placeholder="sourceSearchPlaceholder"
            @search="handleSourceSearch"
            @input="handleSourceInput"
          />
        </div>
      </div>
      <div class="panel-body">
        <div class="item-list">
          <template v-if="isTree">
            <a-tree
              :data="filteredSourceData"
              :checked-keys="selectedSource"
              :checkable="true"
              :selectable="selectable"
              @check="handleSourceTreeCheck"
              @select="handleSourceTreeSelect"
            />
          </template>
          <template v-else>
            <div
              v-for="item in filteredSourceData"
              :key="item.value"
              class="list-item"
              :class="{ 'item-selected': selectedSource.includes(item.value) }"
            >
              <a-checkbox
                :model-value="selectedSource.includes(item.value)"
                @change="() => toggleSourceSelect(item)"
              >
                {{ item.label }}
              </a-checkbox>
            </div>
          </template>
        </div>
      </div>
    </div>

    <!-- 中间操作按钮 -->
    <div class="transfer-operations">
      <a-button
        type="primary"
        :disabled="selectedSource.length === 0"
        @click="moveToTarget"
      >
        <icon-right />
      </a-button>
      <a-button
        type="primary"
        :disabled="selectedTarget.length === 0"
        @click="moveToSource"
      >
        <icon-left />
      </a-button>
    </div>

    <!-- 右侧列表 -->
    <div class="transfer-panel">
      <div class="panel-header">
        <span class="title">{{ targetTitle }}</span>
      </div>
      <div class="panel-body">
        <div class="item-list">
          <template v-if="isTree">
            <a-tree
              :data="filteredTargetData"
              :checked-keys="selectedTarget"
              :checkable="true"
              :selectable="selectable"
              @check="handleTargetTreeCheck"
              @select="handleTargetTreeSelect"
            />
          </template>
          <template v-else>
            <div
              v-for="item in filteredTargetData"
              :key="item.value"
              class="list-item"
              :class="{ 'item-selected': selectedTarget.includes(item.value) }"
            >
              <a-checkbox
                :model-value="selectedTarget.includes(item.value)"
                @change="() => toggleTargetSelect(item)"
              >
                {{ item.label }}
              </a-checkbox>
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import type { TransferItem } from '@/types/common'
import { oaSearch } from '@/apis/meet/component'

// 添加默认导出
defineOptions({
  name: 'CustomTransfer'
})

const props = defineProps<{
  modelValue: string[]
  data: TransferItem[] | any[]
  sourceTitle?: string
  targetTitle?: string
  sourceSearchPlaceholder?: string
  isTree?: boolean
  selectable?: boolean
}>()

const emit = defineEmits(['update:modelValue', 'update:data'])

// 搜索文本
const sourceSearchText = ref('')

// 选中项
const selectedSource = ref<string[]>([])
const selectedTarget = ref<string[]>([])

// 计算源数据和目标数据
const sourceData = computed(() => {
  if (props.isTree) {
    // 对于树形结构，需要过滤掉已选择的节点
    const filterSelectedNodes = (nodes: any[]): any[] => {
      return nodes.map((node) => {
        const isSelected = props.modelValue.includes(node.key)
        if (isSelected) {
          return null
        }
        const children = node.children?.length ? filterSelectedNodes(node.children) : []
        return {
          ...node,
          children: children.filter(Boolean)
        }
      }).filter(Boolean)
    }
    return filterSelectedNodes(props.data)
  }
  return props.data.filter((item) => !props.modelValue.includes(item.value))
})

const targetData = computed(() => {
  if (props.isTree) {
    // 只返回已选择的节点
    const selectedNodes: any[] = []
    const findSelectedNodes = (nodes: any[]) => {
      nodes.forEach((node) => {
        if (props.modelValue.includes(node.key)) {
          selectedNodes.push({
            key: node.key,
            title: node.title,
            children: [],
            type: node.type,
            workId: node.workId,
            avatar: node.avatar,
            deptName: node.deptName
          })
        }
        if (node.children?.length) {
          findSelectedNodes(node.children)
        }
      })
    }
    findSelectedNodes(props.data)
    return selectedNodes
  }
  return props.data.filter((item) => props.modelValue.includes(item.value))
})

// 过滤后的数据
const filteredSourceData = computed(() => {
  if (props.isTree) {
    return sourceData.value
  }
  return sourceData.value.filter((item) =>
    item.label.toLowerCase().includes(sourceSearchText.value.toLowerCase())
  )
})

const filteredTargetData = computed(() => {
  if (props.isTree) {
    return targetData.value
  }
  return targetData.value
})

// 处理树形结构的选中
const handleSourceTreeCheck = (checkedKeys: (string | number)[], _data: any) => {
  selectedSource.value = checkedKeys.map((key) => String(key))
}

const handleTargetTreeCheck = (checkedKeys: (string | number)[], _data: any) => {
  selectedTarget.value = checkedKeys.map((key) => String(key))
}

// 处理树形结构的点击选择
const handleSourceTreeSelect = (selectedKeys: (string | number)[], _data: any) => {
  if (props.selectable) {
    const { node } = _data
    if (node.type === 'user') {
      const key = String(selectedKeys[0])
      const index = selectedSource.value.indexOf(key)
      if (index === -1) {
        selectedSource.value.push(key)
      } else {
        selectedSource.value.splice(index, 1)
      }
    }
  }
}

const handleTargetTreeSelect = (selectedKeys: (string | number)[], _data: any) => {
  if (props.selectable) {
    const { node } = _data
    if (node.type === 'user') {
      const key = String(selectedKeys[0])
      const index = selectedTarget.value.indexOf(key)
      if (index === -1) {
        selectedTarget.value.push(key)
      } else {
        selectedTarget.value.splice(index, 1)
      }
    }
  }
}

// 切换选中状态
const toggleSourceSelect = (item: TransferItem) => {
  const index = selectedSource.value.indexOf(item.value)
  if (index === -1) {
    selectedSource.value.push(item.value)
  } else {
    selectedSource.value.splice(index, 1)
  }
}

const toggleTargetSelect = (item: TransferItem) => {
  const index = selectedTarget.value.indexOf(item.value)
  if (index === -1) {
    selectedTarget.value.push(item.value)
  } else {
    selectedTarget.value.splice(index, 1)
  }
}

// 移动数据
const moveToTarget = () => {
  const newValue = [...props.modelValue, ...selectedSource.value]
  emit('update:modelValue', newValue)
  selectedSource.value = []
}

const moveToSource = () => {
  const newValue = props.modelValue.filter(
    (value) => !selectedTarget.value.includes(value)
  )
  emit('update:modelValue', newValue)
  selectedTarget.value = []
}

// 搜索处理
const handleSourceSearch = async () => {
  if (props.isTree) {
    if (sourceSearchText.value === '') {
      // 如果搜索框为空，恢复原始树形数据
      emit('update:data', { data: props.data, isReset: true })
    } else {
      const res = await oaSearch(sourceSearchText.value)
      if (res.success && res.data) {
        // 将搜索结果转换为树形结构，并过滤掉已选择的节点
        const treeData = res.data
          .filter((item: any) => !props.modelValue.includes(item.userid))
          .map((item: any) => ({
            key: item.userid,
            title: item.name,
            children: [],
            userid: item.userid,
            type: item.type,
            workId: item.workId,
            avatar: item.avatar,
            deptName: item.deptName
          }))

        // 合并搜索结果和已选择的节点
        const mergedData = [...treeData, ...targetData.value]
        emit('update:data', { data: mergedData, isReset: false })
      }
    }
  }
}

const handleSourceInput = async () => {
  if (props.isTree) {
    if (sourceSearchText.value === '') {
      // 如果搜索框为空，恢复原始树形数据
      emit('update:data', { data: props.data, isReset: true })
    } else {
      const res = await oaSearch(sourceSearchText.value)
      if (res.success && res.data) {
        // 将搜索结果转换为树形结构，并过滤掉已选择的节点
        const treeData = res.data
          .filter((item: any) => !props.modelValue.includes(item.userid))
          .map((item: any) => ({
            key: item.userid,
            title: item.name,
            children: [],
            userid: item.userid,
            type: item.type,
            workId: item.workId,
            avatar: item.avatar,
            deptName: item.deptName
          }))

        // 合并搜索结果和已选择的节点
        const mergedData = [...treeData, ...targetData.value]
        emit('update:data', { data: mergedData, isReset: false })
      }
    }
  }
}

// 监听 modelValue 变化，清空选中项
watch(
  () => props.modelValue,
  () => {
    selectedSource.value = []
    selectedTarget.value = []
  }
)
</script>

<style lang="scss" scoped>
.custom-transfer {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
  height: 100%;

  .transfer-panel {
    width: 380px;
    height: 420px;
    border: 1px solid var(--color-border);
    border-radius: 4px;
    background-color: var(--color-bg-2);
    display: flex;
    flex-direction: column;

    .panel-header {
      padding: 12px 16px;
      border-bottom: 1px solid var(--color-border);
      background-color: var(--color-fill-2);

      .title {
        display: block;
        margin-bottom: 8px;
        font-weight: 500;
        color: var(--color-text-1);
      }

      .search-box {
        width: 100%;
      }
    }

    .panel-body {
      flex: 1;
      overflow: hidden;
      padding: 8px;

      .item-list {
        height: 100%;
        overflow-y: auto;

        /* 树节点样式 */
        :deep(.arco-tree-node) {
          width: 100%;
          padding-right: 16px;
        }

        :deep(.arco-tree-node-title) {
          flex: 1;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }

        :deep(.arco-tree-node-drag-icon) {
          display: none;
        }

        :deep(.arco-tree-node-indent + .arco-tree-node-switcher) {
          margin-right: 4px;
        }

        .list-item {
          padding: 8px 12px;
          cursor: pointer;
          border-radius: 4px;
          transition: all 0.2s;

          :deep(.arco-checkbox) {
            width: 100%;
            display: flex;
            align-items: center;

            .arco-checkbox-label {
              flex: 1;
              margin-left: 8px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }

          &:hover {
            background-color: var(--color-fill-2);
          }

          &.item-selected {
            background-color: var(--color-primary-light-1);
          }
        }
      }
    }
  }

  .transfer-operations {
    display: flex;
    flex-direction: column;
    gap: 8px;
    padding: 8px;

    .arco-btn {
      padding: 0 8px;
      height: 32px;
      width: 32px;
    }
  }
}
</style>
